package com.jifeng.api.crud.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jifeng.api.crud.constant.FieldConstant;
import com.jifeng.api.crud.dao.HeartDao;
import com.jifeng.api.crud.entity.HeartEntity;
import com.jifeng.api.crud.entity.TerminalEntity;
import com.jifeng.api.crud.service.HeartService;
import com.jifeng.api.crud.utils.CheckParamsRs;
import com.jifeng.api.utils.PageUtils;
import com.jifeng.api.utils.Query;
import com.jifeng.api.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.Objects;


@Service("heartService")
@Slf4j
public class HeartServiceImpl extends ServiceImpl<HeartDao, HeartEntity> implements HeartService {

    @Autowired
    CheckParamsRs checkParamsRs;

    public String getRequestUrl() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest().getRequestURI();
    }

    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<HeartEntity> page = this.page(
                new Query<HeartEntity>().getPage(params),
                new QueryWrapper<HeartEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R add(Map<String, Object> params) {
        try {
            String iot = Convert.toStr(params.get("iot"));

            /**
             * 校验编号格式
             */
            boolean checkIotRs = checkParamsRs.checkIot(iot);
            if (!checkIotRs) {
                log.warn("path：{}，errMsg：{}", getRequestUrl(), "iot is wrong");
                return R.error(404, "iot is wrong");
            }

            /**
             * 校验是否存在
             */
            HeartEntity heart = this.getOne(new QueryWrapper<HeartEntity>().eq(FieldConstant.T_TERMINAL_IOT, iot), false);
            if (heart != null) {
                log.warn("path：{}，errMsg：{}", getRequestUrl(), "heart has exist");
                return R.error(400, "heart has exist");
            }

            Integer gsm_signal = Convert.toInt(params.get("gsm_signal"));
            Integer gsm_signal_persent = Convert.toInt(params.get("gsm_signal_persent"));
            Date rev_time = Convert.toDate(params.get("rev_time"));

            HeartEntity heartEntity = new HeartEntity();
            heartEntity.setIot(iot);
            heartEntity.setGsmSignal(gsm_signal);
            heartEntity.setGsmSignalPersent(gsm_signal_persent);
            heartEntity.setRevTime(rev_time);
            boolean save = this.save(heartEntity);
            if (save) {
                return R.ok();
            }
            return R.error();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("path：{}，errMsg：{}", "heart入库操作", e.getMessage());
            return R.sysError();
        }
    }

    @Override
    public R myUpdate(HeartEntity heartEntity) {
        try {
            /**
             * 校验编号格式
             */
            boolean checkIotRs = checkParamsRs.checkIot(heartEntity.getIot());
            if (!checkIotRs) {
                log.warn("path：{}，errMsg：{}", getRequestUrl(), "iot is wrong");
                return R.error(404, "iot is wrong");
            }

            /**
             * 校验是否存在
             */
            HeartEntity heart = this.getOne(new QueryWrapper<HeartEntity>().eq(FieldConstant.T_TERMINAL_IOT, heartEntity.getIot()), false);
            if (heart == null) {
                log.warn("path：{}，errMsg：{}", getRequestUrl(), "heart no exist");
                return R.error(400, "heart no exist");
            }

            boolean update = this.update(heartEntity, new UpdateWrapper<HeartEntity>().eq("IOT", heartEntity.getIot()));
            if (update) {
                return R.ok();
            }
            return R.error();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("path：{}，errMsg：{}", "heart修改入库数据操作", e.getMessage());
            return R.sysError();
        }

    }

}